package com.zlk.algorithm.huawei.leetcode.dp.multidimensional;

/**
 * @program: algorithm
 * @ClassName Code53_minPathSum
 * @description:
 * 给定一个包含非负整数的 m x n 网格 grid ，请找出一条从左上角到右下角的路径，使得路径上的数字总和为最小。
 * 说明：每次只能向下或者向右移动一步。
 * @author: slfang
 * @create: 2025-01-16 11:06
 * @Version 1.0
 **/
public class Code53_minPathSum {


    public  int minPathSum(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        int[] dp = new int[m];
        dp[0] = grid[0][0];
        for (int i = 1; i < m; i++) {
            dp[i] = dp[i-1]+grid[0][i];
        }
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < m ; j++) {
                if(j==0){
                    dp[j]+=grid[i][j];
                }else{
                    dp[j]=Math.min(dp[j],dp[j-1])+grid[i][j];
                }
            }
        }
        return dp[m-1];
    }



    // dp[i][j]  dp含义：i,j位置经过路径的最小和
    // dp[i][j] = Math.min(dp[i][j-1],dp[i-1][j])+grid[i][j];
    public  int minPathSum1(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;

        int[][] dp = new int[n][m];
        dp[0][0] = grid[0][0];
        for (int i = 1; i < n; i++) {
            dp[i][0]=dp[i-1][0]+grid[i][0];
        }
        for (int i = 1; i < m; i++) {
            dp[0][i] = dp[0][i-1]+grid[0][i];
        }
        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                if(i>0){
                    dp[i][j] = dp[i-1][j];
                }
                if(j>0){
                    dp[i][j] = Math.min(dp[i][j],dp[i][j-1]);
                }
                dp[i][j]+=grid[i][j];
            }
        }
        return dp[n-1][m-1];
    }
}
